package v1

import (
	"errors"
	"gin-study/app/http/requests"
	"gin-study/app/http/responses"
	"gin-study/app/services"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

var Auth = new(auth)

type auth struct {
	controller
}

func (this *auth) Register(c *gin.Context) interface{} {
	var req *requests.RegisterReq
	err := c.Bind(&req)
	if err != nil {
		return responses.BadRequest(err.Error(), nil)
	}
	user, err := services.Auth.Register(req)
	if err != nil {
		return responses.BadRequest(err.Error(), nil)
	}
	return responses.Ok("ok", gin.H{
		"user": user,
	})
}

func (this *auth) Login(c *gin.Context) interface{} {
	var req *requests.LoginReq
	err := c.Bind(&req)
	if err != nil {
		return responses.BadRequest(err.Error(), nil)
	}
	user, err := services.Auth.Login(req)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return responses.NotFind("找不到这个用户", nil)
	}
	if err != nil {
		return responses.BadRequest(err.Error(), nil)
	}
	token := services.Auth.GetToken(user)
	return responses.Ok("ok", gin.H{
		"user":  user,
		"token": token,
	})
}
